// 文本转图片插件 - 渲染器逻辑

class TextToImageRenderer {
    constructor() {
        this.canvas = document.getElementById('previewCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.currentText = '';
        this.fontSize = 20;
        this.fontWeight = 'normal';
        this.fontStyle = 'normal';
        this.textAlign = 'center';
        this.textColor = '#000000';
        this.imageWidth = 200;
        this.imageHeight = 200;
        this.outputFormat = 'png';
        this.transparentBg = true;
        this.bgColor = '#ffffff';
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.setupDefaults();
        this.updatePreview();
    }
    
    bindEvents() {
        // 文本输入
        const textInput = document.getElementById('textInput');
        textInput.addEventListener('input', (e) => {
            this.currentText = e.target.value;
            this.updatePreview();
        });
        
        // 字体颜色
        const colorPicker = document.getElementById('colorPicker');
        const colorInput = document.getElementById('colorInput');
        colorPicker.addEventListener('input', (e) => {
            this.textColor = e.target.value;
            colorInput.value = e.target.value;
            this.updatePreview();
        });
        colorInput.addEventListener('input', (e) => {
            this.textColor = e.target.value;
            colorPicker.value = e.target.value;
            this.updatePreview();
        });
        
        // 字体大小
        const fontSize = document.getElementById('fontSize');
        const fontSizeDecrease = document.getElementById('fontSizeDecrease');
        const fontSizeIncrease = document.getElementById('fontSizeIncrease');
        
        fontSize.addEventListener('input', (e) => {
            this.fontSize = parseInt(e.target.value) || 20;
            this.updatePreview();
        });
        
        fontSizeDecrease.addEventListener('click', () => {
            const currentSize = parseInt(fontSize.value) || 20;
            const newSize = Math.max(8, currentSize - 1);
            fontSize.value = newSize;
            this.fontSize = newSize;
            this.updatePreview();
        });
        
        fontSizeIncrease.addEventListener('click', () => {
            const currentSize = parseInt(fontSize.value) || 20;
            const newSize = Math.min(200, currentSize + 1);
            fontSize.value = newSize;
            this.fontSize = newSize;
            this.updatePreview();
        });
        
        // 字体粗细
        const fontWeightButtons = document.querySelectorAll('[id^="fontWeight-"]');
        fontWeightButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                fontWeightButtons.forEach(b => b.classList.remove('active'));
                e.target.classList.add('active');
                this.fontWeight = e.target.dataset.weight;
                this.updatePreview();
            });
        });
        
        // 斜体样式
        const fontStyleButton = document.getElementById('fontStyle-italic');
        fontStyleButton.addEventListener('click', (e) => {
            e.target.classList.toggle('active');
            this.fontStyle = e.target.classList.contains('active') ? 'italic' : 'normal';
            this.updatePreview();
        });
        
        // 文本对齐
        const textAlignButtons = document.querySelectorAll('[id^="textAlign-"]');
        textAlignButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                textAlignButtons.forEach(b => b.classList.remove('active'));
                e.target.classList.add('active');
                this.textAlign = e.target.dataset.align;
                this.updatePreview();
            });
        });
        
        // 图片尺寸
        const imageWidth = document.getElementById('imageWidth');
        const imageHeight = document.getElementById('imageHeight');
        imageWidth.addEventListener('input', (e) => {
            this.imageWidth = parseInt(e.target.value) || 200;
            this.updatePreview();
        });
        imageHeight.addEventListener('input', (e) => {
            this.imageHeight = parseInt(e.target.value) || 200;
            this.updatePreview();
        });
        
        // 预设尺寸按钮
        const presetButtons = document.querySelectorAll('.preset-btn');
        presetButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const width = parseInt(e.target.dataset.width);
                const height = parseInt(e.target.dataset.height);
                imageWidth.value = width;
                imageHeight.value = height;
                this.imageWidth = width;
                this.imageHeight = height;
                this.updatePreview();
            });
        });
        
        // 输出格式
        const formatButtons = document.querySelectorAll('.format-btn');
        formatButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                formatButtons.forEach(b => b.classList.remove('active'));
                e.target.classList.add('active');
                this.outputFormat = e.target.dataset.format;
                this.updateBgVisibility();
                this.updatePreview();
            });
        });
        
        // 透明背景
        const transparentBg = document.getElementById('transparentBg');
        const bgColorGroup = document.getElementById('bgColorGroup');
        const bgColorPicker = document.getElementById('bgColorPicker');
        const bgColorInput = document.getElementById('bgColorInput');
        
        transparentBg.addEventListener('change', (e) => {
            this.transparentBg = e.target.checked;
            bgColorGroup.classList.toggle('hidden', this.transparentBg && this.outputFormat === 'png');
            this.updatePreview();
        });
        
        bgColorPicker.addEventListener('input', (e) => {
            this.bgColor = e.target.value;
            bgColorInput.value = e.target.value;
            this.updatePreview();
        });
        
        bgColorInput.addEventListener('input', (e) => {
            this.bgColor = e.target.value;
            bgColorPicker.value = e.target.value;
            this.updatePreview();
        });
        
        // 保存按钮
        const saveBtn = document.getElementById('saveBtn');
        saveBtn.addEventListener('click', () => {
            this.saveImage();
        });
        
        // 复制按钮
        const copyBtn = document.getElementById('copyBtn');
        copyBtn.addEventListener('click', () => {
            this.copyImage();
        });
    }
    
    setupDefaults() {
        // 设置默认值
        document.getElementById('textInput').value = 'Hello World\n欢迎使用文本转图片';
        this.currentText = 'Hello World\n欢迎使用文本转图片';
        document.getElementById('colorPicker').value = '#000000';
        document.getElementById('colorInput').value = '#000000';
        document.getElementById('fontSize').value = '20';
        document.getElementById('imageWidth').value = '200';
        document.getElementById('imageHeight').value = '200';
        document.getElementById('bgColorPicker').value = '#ffffff';
        document.getElementById('bgColorInput').value = '#ffffff';
    }
    
    updateBgVisibility() {
        const transparentBg = document.getElementById('transparentBg');
        const bgColorGroup = document.getElementById('bgColorGroup');
        
        if (this.outputFormat === 'png') {
            transparentBg.disabled = false;
            bgColorGroup.classList.toggle('hidden', this.transparentBg);
        } else {
            transparentBg.disabled = true;
            bgColorGroup.classList.remove('hidden');
        }
    }
    
    updatePreview() {
        // 设置画布尺寸
        this.canvas.width = this.imageWidth;
        this.canvas.height = this.imageHeight;
        
        // 清除画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制背景
        if (this.outputFormat === 'png' && this.transparentBg) {
            // 透明背景 - 不绘制任何背景
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        } else {
            // 彩色背景
            this.ctx.fillStyle = this.bgColor;
            this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        }
        
        // 设置字体样式
        this.ctx.fillStyle = this.textColor;
        let fontStyleString = '';
        if (this.fontStyle === 'italic') {
            fontStyleString += 'italic ';
        }
        if (this.fontWeight !== 'normal') {
            fontStyleString += this.fontWeight + ' ';
        }
        fontStyleString += `${this.fontSize}px Arial, sans-serif`;
        this.ctx.font = fontStyleString;
        this.ctx.textAlign = this.textAlign;
        this.ctx.textBaseline = 'middle';
        
        // 处理文本换行
        const lines = this.currentText.split('\n');
        const lineHeight = this.fontSize * 1.2;
        const totalHeight = lines.length * lineHeight;
        let startY = (this.canvas.height - totalHeight) / 2 + lineHeight / 2;
        
        // 根据对齐方式设置X坐标
        let x;
        switch (this.textAlign) {
            case 'left':
                x = 10;
                break;
            case 'right':
                x = this.canvas.width - 10;
                break;
            default: // center
                x = this.canvas.width / 2;
        }
        
        // 绘制每一行文本
        lines.forEach((line, index) => {
            const y = startY + index * lineHeight;
            this.ctx.fillText(line, x, y);
        });
    }
    
    getImageDataUrl() {
        let mimeType = 'image/png';
        let quality = 1.0;
        
        switch (this.outputFormat) {
            case 'jpeg':
                mimeType = 'image/jpeg';
                quality = 0.9;
                break;
            case 'webp':
                mimeType = 'image/webp';
                quality = 0.9;
                break;
            case 'ico':
            case 'icon':
                mimeType = 'image/png';
                break;
            default:
                mimeType = 'image/png';
        }
        
        return this.canvas.toDataURL(mimeType, quality);
    }
    
    saveImage() {
        try {
            let dataUrl, fileName;
            
            dataUrl = this.getImageDataUrl();
            fileName = `text2image_${new Date().getTime()}.${this.outputFormat}`;
            
            const link = document.createElement('a');
            link.download = fileName;
            link.href = dataUrl;
            link.click();
            
            // 显示成功通知
            this.showNotification('图片保存成功！', 'success');
        } catch (error) {
            console.error('保存图片失败:', error);
            this.showNotification('保存失败，请重试', 'error');
        }
    }
    
    async copyImage() {
        try {
            // 始终使用PNG格式进行复制
            let mimeType = 'image/png';
            let quality = 1.0;
            const dataUrl = this.canvas.toDataURL(mimeType, quality);
            
            // 对于不同格式使用不同的处理方式
            if (navigator.clipboard && window.ClipboardItem) {
                // 现代浏览器支持 ClipboardItem
                const response = await fetch(dataUrl);
                const blob = await response.blob();
                
                await navigator.clipboard.write([
                    new ClipboardItem({ [blob.type]: blob })
                ]);
            } else {
                // 降级处理：直接使用dataUrl
                const img = document.createElement('img');
                img.src = dataUrl;
                
                // 创建临时canvas来处理图像
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = this.canvas.width;
                tempCanvas.height = this.canvas.height;
                const tempCtx = tempCanvas.getContext('2d');
                
                // 绘制背景（PNG格式始终有背景）
                tempCtx.fillStyle = this.transparentBg ? 'rgba(0,0,0,0)' : this.bgColor;
                tempCtx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
                
                // 绘制当前画布内容
                tempCtx.drawImage(this.canvas, 0, 0);
                
                tempCanvas.toBlob(async (blob) => {
                    if (blob && navigator.clipboard && navigator.clipboard.write) {
                        try {
                            await navigator.clipboard.write([
                                new ClipboardItem({ [blob.type]: blob })
                            ]);
                            this.showNotification('图片已复制到剪贴板！', 'success');
                        } catch (error) {
                            console.error('Clipboard API失败:', error);
                            // 最后降级方案：使用execCommand
                            try {
                                const img = document.createElement('img');
                                img.src = dataUrl;
                                document.body.appendChild(img);
                                const range = document.createRange();
                                range.selectNode(img);
                                window.getSelection().removeAllRanges();
                                window.getSelection().addRange(range);
                                document.execCommand('copy');
                                window.getSelection().removeAllRanges();
                                document.body.removeChild(img);
                                this.showNotification('图片已复制到剪贴板！', 'success');
                            } catch (fallbackError) {
                                console.error('所有复制方法都失败:', fallbackError);
                                this.showNotification('复制失败，请重试', 'error');
                            }
                        }
                    } else {
                        // 如果blob为空或不支持Clipboard API
                        this.showNotification('复制失败，请重试', 'error');
                    }
                }, mimeType, quality);
                return;
            }
            
            this.showNotification('图片已复制到剪贴板！', 'success');
        } catch (error) {
            console.error('复制图片失败:', error);
            this.showNotification('复制失败，请重试', 'error');
        }
    }
    
    showNotification(message, type = 'info') {
        // 简单的通知实现
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            z-index: 10000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            ${type === 'success' ? 'background: #4CAF50;' : 
              type === 'error' ? 'background: #f44336;' : 
              'background: #2196F3;'}
        `;
        notification.textContent = message;
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.textToImageRenderer = new TextToImageRenderer();
});
